/**
* 全站权限配置
*/
import store from './store'
import router from './router'
import { validatenull } from '@/utils/validate'
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { Message } from 'element-ui'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/register','/content/index'] // no redirect whitelist



console.log("---------permission里面的store--------------")
console.log(store)








router.beforeEach(async(to, from, next) => {

  // start progress bar
  NProgress.start()

  const meta = to.meta || {};
  // set page title
  document.title = getPageTitle( !validatenull(meta) ? meta.title : "")

  // determine whether the user has logged in
  const hasToken = getToken()

  console.log("跳转时是否有token:"+hasToken)

  if (hasToken) {
    if (to.path === '/login') {
      //如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      //如果用户信息为空则获取用户信息，获取用户信息失败，跳转到登录页
      if(store.getters.roles.length === 0){

        try{
          await store.dispatch('user/GetUserInfo')

          console.log("-----permission----执行到next---无roles----------")

          next({ ...to, replace:true })
        }catch(error){
          await store.dispatch('user/FedLogOut');
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`);
          NProgress.done()
        }

      }else{
        /************************************************
        ********路由跳转时增加一条tagView,参考guns*********
        *************************************************/
        console.log("%cpermission执行到next拿到to信息","background:#f00;color:#fff")
        console.log(to)
        console.log(meta)

        //判断是否加入到顶部tab
        if(meta.isTab && meta.isTab !== false){
          store.dispatch('tagsView/addView',to)
        }
        
        next();
      }


    }
  } else {
    /* has no token*/

    

    if (whiteList.indexOf(to.path) !== -1 || ( meta.isAuth === false)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
